#include "loginWidget.h"
#include "ui_IMA_widget.h"


loginViewWidget::loginViewWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setFixedSize(810,460);

    //设置登录窗口标题栏
    this->setWindowTitle("智慧医疗预约系统");
    this->setWindowIcon(QIcon(":/res/login.svg"));
    getConnect();
    init();


}

loginViewWidget::~loginViewWidget()
{
    delete ui;
}

//数据库连接
void loginViewWidget::getConnect(){
    //数据库连接
    db = QSqlDatabase::addDatabase("QMYSQL","connection");
    db.setHostName("127.0.0.1");
    db.setPort(3306);
    db.setDatabaseName("IMA_System");
    db.setUserName("root");
    db.setPassword("123456");
    if(db.open()){
        qDebug()<<"数据库连接成功";
    }else{
        qDebug()<<"数据库连接失败"<<"失败原因："<<db.lastError().text();
    }
}


void loginViewWidget::init()
{
    //隐藏标题栏
    this->setWindowFlags(Qt::FramelessWindowHint);
    // 使窗口可拖动
    this->setMouseTracking(true);
    oldPos = QPoint(0, 0);

    // 创建整体布局
    mainLayout = new QHBoxLayout(this);

    // 调整布局的边距和间距
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);

    // --------------------------左侧布局开始-----------------------------------------------
    //左边
    leftWidget = new QWidget;
    leftWidget->setFixedSize(410,460);   

    // 左侧图标布局
    leftLogoLayout = new QVBoxLayout(leftWidget);
    // 调整布局的边距和间距
    leftLogoLayout->setContentsMargins(0, 0, 0, 0);
    leftLogoLayout->setSpacing(0);

    // 创建左侧图标部件
    leftLabel = new QLabel;
    //设置左边图片
    leftLabel->setPixmap(QPixmap(":/res/loginLeft.jpg"));
    leftLabel->setScaledContents(true);
    // 将图片居中显示
    leftLabel->setAlignment(Qt::AlignCenter);

    //将图片table加到左侧布局中
    leftLogoLayout->addWidget(leftLabel);
    //将左侧布局加入到整理布局中
    mainLayout->addWidget(leftWidget);


    // --------------------------右侧布局开始-----------------------------------------------
    // 右侧布局
    rightWidget = new QGroupBox;
    rightWidget->setFixedSize(400,460);
    rightWidget->setStyleSheet("background-color:white;");
    rightWidget->setContentsMargins(0,0,0,0);

    // 右侧登录表布局
    RightLayout = new QVBoxLayout(rightWidget);
    // 调整布局的边距和间距
    RightLayout->setContentsMargins(0, 0, 0, 0);
    RightLayout->setSpacing(22);

    QWidget *cm = new QWidget;
    cm->setStyleSheet("background-color:white;");
    cm->setFixedSize(397,30);
    // 创建一个新的水平布局用于标题栏按钮
    QHBoxLayout *titleBarLayout = new QHBoxLayout(cm);

    // 设置布局的边距和间距，使按钮更靠近顶部和右侧
    titleBarLayout->setContentsMargins(0, 0, 0, 0);
    titleBarLayout->setSpacing(0);

    shutdownBtn = new QPushButton("✕");
    minimizeBtn = new QPushButton("—");
    // 设置按钮的大小为 30x30
    shutdownBtn->setFixedSize(30, 30);
    minimizeBtn->setFixedSize(30, 30);
    shutdownBtn->setStyleSheet(
                "QPushButton {"
                "background-color: rgba(0, 0, 0, 0);"
                "border-radius: 8px;"
                "}"
                "QPushButton:hover {"
                "background-color: red;"
                "color: white;"
                "}");
    minimizeBtn->setStyleSheet(
                "QPushButton {"
                "background-color: rgba(0, 0, 0, 0);"
                "border-radius: 8px;"
                "}"
                "QPushButton:hover {"
                "background-color: rgba(100, 100, 100, 50);"
                "}");

    // 创建一个水平伸缩项，将标题栏布局推到右侧
    QSpacerItem *spacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
    // 先添加伸缩项，再添加按钮
    titleBarLayout->addItem(spacer);
    titleBarLayout->addWidget(minimizeBtn);
    titleBarLayout->addWidget(shutdownBtn);

    // 将标题栏布局添加到右侧布局的顶部
    RightLayout->addWidget(cm);

    //最小化按钮绑定事件
    connect(minimizeBtn, &QPushButton::clicked, this, &loginViewWidget::on_minimizeBtn_clicked);
    //关闭按钮绑定事件
    connect(shutdownBtn, &QPushButton::clicked, this, &loginViewWidget::on_shutdownBtn_clicked);

    // 标题
    titleLabel = new QLabel("门诊挂号管理系统");
    //设置对齐方式：居中对齐
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 30px;"
                              "color: rgb(7, 7, 7);"
                              "font: 75 25pt '等线';"
                              );
    titleLabel->setMaximumHeight(40);
    //将标题添加到右侧布局中
    RightLayout->addWidget(titleLabel);

    // 副标题
    subTitleLabel = new QLabel("数字引领医疗信息变革");
    subTitleLabel->setStyleSheet(
                                "color: rgb(180, 180, 180);"
                                "font: 12pt '等线';"
                                );
    subTitleLabel->setAlignment(Qt::AlignCenter);
    subTitleLabel->setMaximumHeight(20);
    RightLayout->addWidget(subTitleLabel);

    // 用户名输入框
    userNameEdit = new QLineEdit;
    userNameEdit->setPlaceholderText("请输入用户名") ;
    //设置图标
    userNameEdit->setStyleSheet("QLineEdit{"
                                    "margin-left:60px;"
                                    "margin-top:20px;"
                                    "max-width:230px;"
                                    "padding-left: 40px;"
                                    "background-image: url(:/res/name.svg); "
                                    "background-repeat: no-repeat;"
                                    "background-position: left center;"
                                    "background-size: 18px 18px;"
                                    "height:40px;"
                                    "background-color:white;"
                                    "font: 12pt 'Arial';"
                                "}");
//    userNameEdit->setMaximumWidth(300);

    userNameEdit->setMaxLength(11);
    //将用户名标签加入到右侧布局中
    RightLayout->addWidget(userNameEdit);


    // 连接用户名输入框的失去焦点事件
     connect(userNameEdit, &QLineEdit::editingFinished, this, &loginViewWidget::on_userNameEdit_lostFocus);


    // 密码输入框
    passWordEdit = new QLineEdit;
    passWordEdit->setPlaceholderText("请输入密码");
    //设置图标
    passWordEdit->setStyleSheet("QLineEdit{"
                                    "margin-left:60px;"
                                    "margin-top:15px;"
                                    "max-width:230px;"
                                    "padding-left: 40px;"
                                    "background-image: url(:/res/pass.svg); "
                                    "background-repeat: no-repeat; "
                                    "background-position: left center;"
                                    "background-size: 18px 18px;"
                                    "height:40px;"
                                    "background-color:white;"
                                    "font: 12pt 'Arial';"
                                "}");

    //设置密码，Password是QLineEdit头文件自带功能；可隐藏输入的密码
    passWordEdit->setEchoMode(QLineEdit::Password);
    passWordEdit->setMaxLength(16);
    passWordEdit->setMaximumWidth(300);

    //临时测试使用，一直显示账号密码------------------------------------------------------
    userNameEdit->setText("admin");
    passWordEdit->setText("admin");
    //---------------------------------------------------------------------------------

    // 将 pwdShow 作为 QLineEdit 的自定义按钮添加到右侧
    showButton = new QToolButton(passWordEdit);
    showButton->setFixedSize(20, 20);
    showButton->setCursor(Qt::ArrowCursor);
    showButton->setStyleSheet("QToolButton {"
                              "border: none;"
                              "padding: 2px;"
                              "background-color: transparent;"
                              "image: url(:/res/pwdShow.svg);"
                              "}");

    // 调整 showButton 的位置
    int xOffset = passWordEdit->width() - showButton->width() + 20;
    int yOffset = 28;
    showButton->setGeometry(xOffset, yOffset, showButton->width(), showButton->height());

    // 显示密码 按钮的 按下和松开事件
    connect(showButton, &QToolButton::pressed, [this]() {
        passWordEdit->setEchoMode(QLineEdit::Normal);
    });
    connect(showButton, &QToolButton::released, [this]() {
        passWordEdit->setEchoMode(QLineEdit::Password);
    });

    //将密码输入框添加到右侧布局
    RightLayout->addWidget(passWordEdit);


    // 记住密码
    rememberCheckBox = new QCheckBox("记住密码");
    // 忘记密码
    forgetBtn = new QPushButton("忘记密码");
    rememberCheckBox->setStyleSheet(
                                "margin-left:60px;"
                            );
    forgetBtn->setStyleSheet(
                            "QPushButton {"
                                    "color:gray;"
                                    "border: none;"
                                    "background-repeat: no-repeat;"
                            "}"
                            "QPushButton:hover{"
                                    "color:blue;"
                            "}"
                            );
    connect(forgetBtn,&QPushButton::clicked,this, &loginViewWidget::on_reSetPass_clicked);

    //创建一个水平布局
    checkBoxLayout = new QHBoxLayout;
    checkBoxLayout->addWidget(rememberCheckBox);
    checkBoxLayout->addWidget(forgetBtn);

    //将两个复选框放到右侧总体布局中；
    RightLayout->addLayout(checkBoxLayout);

    //登录按钮
    loginButton = new QPushButton("登录");
    //使按钮可以获得焦点，从而能够响应键盘事件。
    loginButton->setFocusPolicy(Qt::StrongFocus);
    loginButton->setStyleSheet(
                            "QPushButton{"
                                    "margin-left:60px;"
                                    "max-width:270px;"
                                    "height:35px;"
                                    "background-repeat: no-repeat;"
                                    "background-color: rgb(54, 99, 254);"
                                    "color:white;"
                                    "font-size:15px;"
                                    "font: 75 14pt 'Microsoft YaHei UI';"
                            "}"
                        );

    //将按钮添加到右边整体布局中
    RightLayout->addWidget(loginButton);

    //错误提示文本
    msg = new QLabel;
    //设置对齐方式：居中对齐
    msg->setFixedSize(398,35);
    msg->setAlignment(Qt::AlignCenter);
    msg->setStyleSheet("QLabel{"
                            "color:red;"
                            "background-color:white;"
                            "font-size:15px;"
                            "padding-bottom:20px;"
                       "}");
    RightLayout->addWidget(msg);

    // 将右侧布局添加到主布局
    mainLayout->addWidget(rightWidget);
    //音频初始化
    loginMp3 = new QMediaPlayer(this);
    //登录按钮连接
    connect(loginButton, &QPushButton::clicked, this, &loginViewWidget::on_login_clicked);
}

//点击登录按钮
void loginViewWidget::on_login_clicked()
{
    //获取输入框的账号
    username = userNameEdit->text();
    //获取输入框的密码
    password = passWordEdit->text();
    //是否选择记住密码
    flag = rememberCheckBox->isChecked();

    //创建数据库操作指针并关联数据库
    QSqlQuery query(db);
    query.prepare("SELECT username, PASSWORD FROM USER WHERE username = :username AND password = :password");
    query.bindValue(":username", username);
    query.bindValue(":password", password);

    // 执行查询操作
    if (query.exec()) {
        if (query.next()) {
            userNameEdit->clear();
            passWordEdit->clear();
//            msg->setText("登录成功！");
            //如果选择了记住密码
            if(flag){
                query.prepare("UPDATE USER SET remember_pwd = '1' WHERE username = :username;");
                query.bindValue(":username", username);
                query.exec();
            }else{
                query.prepare("UPDATE USER SET remember_pwd = '0' WHERE username = :username;");
                query.bindValue(":username", username);
                query.exec();
            }
            //关闭当前的页面
            this->close();
            //创建主页面
            manageFace* manageView = new manageFace;
            //登录音效设置
            // QSoundEffect::play(":/res/login.wav");
            // QSoundEffect::play(":/res/window.wav");
            //打开主页面
            manageView->show();
            db.close();
        } else {
            msg->setText("用户名或密码错误！");
            userNameEdit->clear();
            passWordEdit->clear();
            QTimer *timer = new QTimer(this);
            timer->start(1000);
            connect(timer, &QTimer::timeout, [timer,this]() {
                msg->setText("");
                timer->deleteLater();
            });
        }
    } else {
        QMessageBox::critical(this, "错误", "数据库查询失败");
    }

}

//找回密码单击事件
void loginViewWidget::on_reSetPass_clicked()
{
    resetPassWord* repass = new resetPassWord;
    repass->setWindowModality(Qt::ApplicationModal);
    repass->show();

}
// 用户名输入框失去焦点事件
void loginViewWidget::on_userNameEdit_lostFocus()
{
    QString username = userNameEdit->text();
//    qDebug() << "用户名输入框失去焦点: " << username;

    //使用了数据库，后续用连接池优化------------------------------------------------
    QSqlQuery query(db);
    query.prepare("SELECT username, PASSWORD, remember_pwd FROM USER WHERE username = :username AND remember_pwd = '1';");
    query.bindValue(":username", username);
    if (query.exec()) {
        if (query.next()) {
            //如果是记住密码，就显示密码
            QString password = query.value("PASSWORD").toString();
            passWordEdit->setText(password);
            rememberCheckBox->setChecked(true);
        }else{
            //如果查询不到，那就清空密码和记住密码
            //避免输入其他账号，还默认使用上一个账号的密码默认记住密码
            passWordEdit->clear();
            rememberCheckBox->setChecked(false);
        }
    }else{
        QMessageBox::critical(this, "错误", "数据库查询失败");
    }
}

// 鼠标按下事件处理函数
void loginViewWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        oldPos = event->globalPosition().toPoint() - frameGeometry().topLeft();

    }
    QWidget::mousePressEvent(event);
}


// 鼠标移动事件处理函数
void loginViewWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        move(event->globalPosition().toPoint() - oldPos);
    }
    QWidget::mouseMoveEvent(event);
}
//按下回车键登录
void loginViewWidget::keyPressEvent(QKeyEvent* event)
{
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
    {
        if (loginButton->isEnabled())
        {
            loginButton->click();
        }
    }
    QWidget::keyPressEvent(event);
}

//关闭
void loginViewWidget::on_shutdownBtn_clicked()
{
    close();
}
//最小化
void loginViewWidget::on_minimizeBtn_clicked()
{
    showMinimized();
}
